package com.watf.functions.gs;

import org.testng.Assert;
import org.testng.Reporter;

import com.thoughtworks.selenium.Selenium;
import com.watf.functions.core.DefaultBasicFuncs;
import com.watf.pages.gs.MainFrame;
import com.watf.pages.gs.XMLDTDS;

/*
 * FileName: XMLDTDSFuncs.java
 * Author:Jester
 * Methods: XMLDTDNew(),XMLDTDRemove() 
 * 
 * History:
 * Date       Comments       Updater
 * 2011-6-2   First Draft    Jester
 */
public class XMLDTDSFuncs extends DefaultBasicFuncs {
	
	/**
	 * Go to 'XML DTDs' page
	 * @author bear
	 */
	public void gotoXMLDTDSPage( Selenium selenium ) {
		selenium.click( MainFrame.DataSources_MENU );
		selenium.click( MainFrame.XMLDTDS_SUBMENU );
		selenium.waitForPageToLoad( CommonFuncs.SHORT_WAIT );
		Assert.assertEquals( selenium.getTitle(), XMLDTDS.TITLE );
	}

	/**
	 * Create a new XML DTD
	 *
	 * @return the name of the created XML DTD
	 */
	public String newXMLDTD(Selenium selenium, String XMLDTDProfiles)
			throws Exception {
		selenium.click(XMLDTDS.New_BUTTON);
		selenium.waitForPageToLoad(CommonFuncs.SHORT_WAIT);

		String[] iXMLDTDProfiles = XMLDTDProfiles.split(",");
		String iXMLDTDName = null;

		for (String iXMLDTDProfile : iXMLDTDProfiles) {
			String[] ivalue = iXMLDTDProfile.split("=");
			String iFieldName = ivalue[0].trim();
			String iFieldValue = ivalue[1].trim();

			if (iFieldName.equals("name")) {
				selenium.type(XMLDTDS.Name_TEXT_FIELD, iFieldValue);
				iXMLDTDName = iFieldValue;
			} else if (iFieldName.equals("description")) {
				selenium.type(XMLDTDS.Description_TEXT_FIELD, iFieldValue);
			}
		}
		selenium.click(XMLDTDS.Save_BUTTON);
		if (selenium.isAlertPresent()) {
			selenium.getAlert();
		}
		selenium.waitForPageToLoad(CommonFuncs.SHORT_WAIT);
		
		selenium.click(XMLDTDS.Return_BUTTON);
		selenium.waitForPageToLoad(CommonFuncs.SHORT_WAIT);

		Assert.assertTrue( findElementsOnTables(selenium, "link=" + iXMLDTDName),
				"Failed to create XML DTD " + iXMLDTDName );
		
		return iXMLDTDName;
	}

	/**
	 * Remove a XML DTD
	 * 
	 * @return true if the specified XML DTD is removed rightly; false if the specified XML DTD is not found.
	 */
	public boolean XMLDTDRemove(Selenium selenium, String iXMLDTDName)
			throws Exception {
		if ( selectRadioButtonFromTable(selenium, XMLDTDS.XMLDTDS_TABLE,iXMLDTDName) ) {
			selenium.click(XMLDTDS.Remove_BUTTON);
			Reporter.log( "The confimation when removing XML DTD: " + selenium.getConfirmation() );
			selenium.waitForPageToLoad( CommonFuncs.SHORT_WAIT );
			Assert.assertFalse( findElementsOnTables( selenium, "link=" + iXMLDTDName ),
					"Failed to remove XML DTD!" );
			return true;
		} else {
			Reporter.log( "Can not find the XML DTD: " + iXMLDTDName + "!" );
			return false;
		}
	}
}
